package com.army.study.devices;


import com.army.study.ResourceTable;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.distributedschedule.interwork.DeviceInfo;
import java.util.List;

/**
 * 设备选择对话框
 */
public class SelectDeviceDialog {
    private static final int DIALOG_WIDTH = 840;
    private static final int DIALOG_HEIGHT = 900;

    private CommonDialog commonDialog;

    public SelectDeviceDialog(Context context, List<DeviceInfo> devices, SelectResultListener listener) {
        initView(context, devices, listener);
    }

    private void initView(Context context, List<DeviceInfo> devices, SelectResultListener listener) {
        // 创建一个公共对话框
        commonDialog = new CommonDialog(context);
        // 设置对齐方式居中
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        // 设置对话框尺寸
        commonDialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        // 设置对话框自动关闭
        commonDialog.setAutoClosable(true);
        // 加载XML布局文件
        Component dialogLayout =
                LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_select_device, null, false);
        // 设置对话框内容
        commonDialog.setContentCustomComponent(dialogLayout);
        // 查找到列表容器
        if (dialogLayout.findComponentById(ResourceTable.Id_list_devices) instanceof ListContainer) {
            // 获取列表容器对象
            ListContainer devicesListContainer =
                    (ListContainer) dialogLayout.findComponentById(ResourceTable.Id_list_devices);
            // 设备列表适配器
            DevicesListAdapter devicesListAdapter = new DevicesListAdapter(devices, context);
            // 设置设备列表容器项提供者
            devicesListContainer.setItemProvider(devicesListAdapter);
            // 设置设备列表项单击事件
            devicesListContainer.setItemClickedListener((listContainer, component, position, id) -> {
                // 回调选择的设备信息
                listener.callBack(devices.get(position));
                // 关闭对话框
                commonDialog.hide();
            });
        }
        dialogLayout.findComponentById(ResourceTable.Id_cancel).setClickedListener(component -> {
            // 关闭对话框
            commonDialog.hide();
        });
    }

    // 显示对话框
    public void show() {
        commonDialog.show();
    }

    /**
     * 内部接口, 选择设备后回调事件
     */
    public interface SelectResultListener {
        void callBack(DeviceInfo deviceInfo);
    }
}
